package cn.time1024.time_app.ui.notebook

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import cn.time1024.time_app.databinding.FragmentNotebookBinding
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class NotebookFragment : Fragment() {

    private var _binding: FragmentNotebookBinding? = null
    private val binding get() = _binding!!
    private lateinit var adapter: NotebookAdapter
    private var pageNo = 1
    private var pageSize = 10
    private var isLoading = false
    private var hasMore = true

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentNotebookBinding.inflate(inflater, container, false)
        setupList()
        setupActions()
        loadPage(true)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView(); _binding = null
    }

    private fun setupList() {
        adapter = NotebookAdapter(
            onEdit = { item -> showEditDialog(item) },
            onDelete = { item ->
                RetrofitClient.api.deleteNote(ApiService.NoteSubmit(noteId = item.noteId))
                    .enqueue(simpleVoidCallback("删除成功", "删除失败"))
            }
        )
        binding.rvNotes.layoutManager = LinearLayoutManager(requireContext())
        binding.rvNotes.adapter = adapter
        binding.swipeRefresh.setOnRefreshListener { loadPage(true) }
    }

    private fun setupActions() {
        binding.fabAdd.setOnClickListener { showAddDialog() }
    }

    private fun loadPage(reset: Boolean) {
        if (isLoading) return
        isLoading = true
        if (reset) { pageNo = 1; hasMore = true }
        RetrofitClient.api.getNotesPage(pageNo = pageNo, pageSize = pageSize)
            .enqueue(object : Callback<ResponseEnvelope<ApiService.PageResult<ApiService.NoteItem>>> {
                override fun onResponse(call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.NoteItem>>>, response: Response<ResponseEnvelope<ApiService.PageResult<ApiService.NoteItem>>>) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                    val data = response.body()?.data
                    val list = data?.rows ?: emptyList()
                    val total = data?.totalRows ?: 0
                    binding.tvTotal.text = "共 ${total} 条"
                    if (reset) adapter.replaceAll(list) else adapter.appendAll(list)
                    hasMore = (adapter.itemCount < total)
                    if (hasMore) pageNo += 1
                }
                override fun onFailure(call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.NoteItem>>>, t: Throwable) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                    Toast.makeText(requireContext(), "网络错误：${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun showAddDialog() {
        val etTitle = EditText(requireContext()).apply { hint = "标题" }
        val etContent = EditText(requireContext()).apply { hint = "内容" }
        val etCategory = EditText(requireContext()).apply { hint = "分类(可选)" }
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etTitle)
            addView(etContent)
            addView(etCategory)
        }
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("新增笔记")
            .setView(wrapper)
            .setPositiveButton("确定") { _, _ ->
                val title = etTitle.text?.toString()?.trim()
                val content = etContent.text?.toString()?.trim()
                val category = etCategory.text?.toString()?.trim()
                if (title.isNullOrEmpty()) {
                    Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show(); return@setPositiveButton
                }
                RetrofitClient.api.addNote(ApiService.NoteSubmit(title = title, content = content, category = category))
                    .enqueue(simpleVoidCallback("添加成功", "添加失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showEditDialog(item: ApiService.NoteItem) {
        val etTitle = EditText(requireContext()).apply { hint = "标题"; setText(item.title ?: "") }
        val etContent = EditText(requireContext()).apply { hint = "内容"; setText(item.content ?: "") }
        val etCategory = EditText(requireContext()).apply { hint = "分类(可选)"; setText(item.category ?: "") }
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etTitle)
            addView(etContent)
            addView(etCategory)
        }
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("编辑笔记")
            .setView(wrapper)
            .setPositiveButton("保存") { _, _ ->
                val title = etTitle.text?.toString()?.trim()
                val content = etContent.text?.toString()?.trim()
                val category = etCategory.text?.toString()?.trim()
                if (title.isNullOrEmpty()) {
                    Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show(); return@setPositiveButton
                }
                RetrofitClient.api.editNote(ApiService.NoteSubmit(noteId = item.noteId, title = title, content = content, category = category))
                    .enqueue(simpleVoidCallback("保存成功", "保存失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun simpleVoidCallback(successMsg: String, failMsg: String): Callback<ResponseEnvelope<Any?>> {
        binding.swipeRefresh.isRefreshing = true
        return object : Callback<ResponseEnvelope<Any?>> {
            override fun onResponse(call: Call<ResponseEnvelope<Any?>>, response: Response<ResponseEnvelope<Any?>>) {
                binding.swipeRefresh.isRefreshing = false
                val body = response.body()
                val ok = (body?.success == true) || (body?.code == "00000")
                if (response.isSuccessful && ok) {
                    Toast.makeText(requireContext(), successMsg, Toast.LENGTH_SHORT).show()
                    loadPage(true)
                } else {
                    Toast.makeText(requireContext(), body?.message ?: failMsg, Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<ResponseEnvelope<Any?>>, t: Throwable) {
                binding.swipeRefresh.isRefreshing = false
                Toast.makeText(requireContext(), "$failMsg：${t.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

